/**
 * MenuScene.m
 * 
 * 
 * Revision History: 
 *
 * Date     Author       Version   Changes
 * ======== ============ ========= ================================================================
 * 03/25/10 Steve Hu     2.0       Initial version.
 *								   1. Implemented mock-up menus to be used for entering GameScene 
 *									  and UploadScoreScene.
 * 03/27/10 Robin Mahony 2.1       Modifed MenuScene to play music, and added MenuLayer to use custom background
 * ======== ============ ========= ================================================================
 *
 */

#import "MenuScene.h"
#import "MenuItem.h"
#import "Menu.h"
#import "GameScene.h"
//#import "ScoreScene.h"
#import "TutorialScene.h"
#import <SystemConfiguration/SystemConfiguration.h>
#include <netdb.h>

@implementation MenuScene

- (id) init
{
    self = [super init];
	
    if (self != nil) 
	{
		Sprite *bg = [Sprite spriteWithFile:@"newMenufree.png"];
		[bg setPosition:ccp (160, 240) ];
		[self addChild:bg z:0];
		
		/* Set the depth ordering to 1, so everything will be on top of this background layer  */
        Layer *layer = [MenuLayer node];
		[self addChild:layer z:1];
		
	
    }
    return self;
}

@end

@interface MenuLayer (private)

- (void) processTaps;
- (void) runLayer;
- (BOOL) connectedToNetwork ;

@end


@implementation MenuLayer

@synthesize player;
@synthesize path;

- (id) init 
{
    self = [super init];
	
	if (self != nil) 
	{
		[self runLayer];
		/* This tells Cocos2d to call our touch event handlers.  */
		isTouchEnabled = YES;
		touch_Type = nullType;
    }
	
	return self;
}

/* This method removes all objects added to the scene, indicating you want Cocos2D to “clean up” by 
 releasing the objects as well, and then you must call the dealloc method of the superclass  */
- (void) dealloc 
{
	[self.player release];
	[self removeAllChildrenWithCleanup:YES];
	[super dealloc];
}

- (void) runLayer
{
	self.path = [[NSBundle mainBundle] pathForResource:@"menuMusic" ofType:@"mp3"];
	self.player = [[[AVAudioPlayer alloc] initWithContentsOfURL: [NSURL fileURLWithPath:self.path] error:&error] retain];
	if (!self.player) 
	{
		NSLog(@"Error %@", [error localizedDescription]); 
		return;
	}
	[self.player prepareToPlay];
	[self.player setNumberOfLoops:999999];
	
	/* This line retrieves the status that determines whether music was left on or off at the start menu.  */
	musicStatus = [[NSUserDefaults standardUserDefaults]boolForKey:@"musicStatus"];
	 /* For use with keeping the music on/off status between the game and main menu in sync.  */
	if(musicStatus == NO)
	{
		//Do nothing if music is supposed to be off
	}
	else 
	{
		[player play];
	}

	
	
	[self schedule:@selector(updateBoard:) interval: 1.0 / 60.0];
	
}

/* This method is the menu scene loop.  */
- (void) updateBoard:(ccTime)dt 
{
	[self processTaps];
}

/* Define the single tap region, and listen to the events generated 
 when the user lifts their finger off the screen.  */
- (BOOL) ccTouchesEnded:(NSSet *) touches withEvent:(UIEvent *) event 
{
	
	UITouch *touch = [touches anyObject];
	CGPoint point = [touch locationInView: [touch view]];
	
	/* To compare Cocos2D Sprite positions to UITouch coordinates,
	 we need to flip UITouch y coordinate upside down for portrait mode.  */
	point.y = 480 - point.y;
	
	
    /* Define the Start, High Scores, Tutorial, and Music buttons control area to match the background image.  */
	if (((int) point.y > 282) && ((int) point.y < 344) && ((int) point.x > 75) && ((int) point.x < 260))
	{
		touch_Type = start;
	}
	else if (((int) point.y > 220) && ((int) point.y < 274) && ((int) point.x > 75) && ((int) point.x < 260))
	{
		touch_Type = full_version;
	}
	else if (((int) point.y > 145) && ((int) point.y < 204) && ((int) point.x > 75) && ((int) point.x < 260))
	{
		touch_Type = tutorial;
	}
	
	else if (((int) point.y > 70) && ((int) point.y < 130) && ((int) point.x > 75) && ((int) point.x < 260))
	{
		touch_Type = music;
	}
	else if (((int) point.y > 0) && ((int) point.y < 60) && ((int) point.x > 75) && ((int) point.x < 260))
	{
		touch_Type = quit;
	}
	
	
	return kEventHandled;
}


/* This method examines the touchType variable that was set earlier by the 
 ccTouchesEnded:withEvent: method. The code resets the touchType variable 
 immediately so that you don't forget and are ready for the next touch event.  */
- (void) processTaps 
{	
	/* Setup the highlighted index variable: highlighScore.  */
	if (touch_Type == start) 
	{
		NSUserDefaults *boolDefault = [NSUserDefaults standardUserDefaults];
		[boolDefault setBool:musicStatus forKey:@"musicStatus"];
		
		touch_Type = nullType;
		NSLog(@"Start game");
		/* Stop the menu loop.  */
		[self unschedule:@selector (updateFrame:)];
		[player stop];
		[[Director sharedDirector] replaceScene:[GameScene node]];
		
    } 
	else if (touch_Type == full_version) 
	{
		if ([self connectedToNetwork] )
		{
		touch_Type = nullType;
		NSLog(@"View full version website");
		/* Stop the menu loop.  */
		[self unschedule:@selector (updateFrame:)];
		[player stop];
		
			//[[Director sharedDirector] pause];
			[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://itunes.apple.com/ca/app/s-i-g-m-a/id375614026?mt=8"]];
		}
	} 
	else if (touch_Type == tutorial)
	{
		NSLog(@"Tutorial");
		touch_Type = nullType;
		[self unschedule:@selector (updateFrame:)];
		[player stop];
		[[Director sharedDirector] replaceScene:[TutorialScene node]];
		
	}
	else if(touch_Type == music)
	{
		NSLog(@"Toggle Music");
		if(player.playing == YES)
		{
			musicStatus = NO;
			[player pause];
		}
		else 
		{
			musicStatus = YES;
			[player play];
		}

		
		touch_Type = nullType;
		
	}
	
	else if (touch_Type == quit)
	{
		NSUserDefaults *boolDefault = [NSUserDefaults standardUserDefaults];
		[boolDefault setBool:YES forKey:@"musicStatus"];
		[[NSUserDefaults standardUserDefaults] synchronize];
		touch_Type = nullType;
		[self unschedule:@selector (updateFrame:)];
		[player stop];
		exit(0); /* Terminate the application.  */
	}

	
}

/* This method checks to ensure an internet connection is available on the device.  
 Returns NO if no connection exits,  YES if there is a connection.  */
- (BOOL) connectedToNetwork 
{
	/* Create zero addy.  */
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;
    
    /* Recover reachability flags.  */
    SCNetworkReachabilityRef defaultRouteReachability 
	= SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    
    if (!didRetrieveFlags)
    {
        printf("Error. Could not recover network reachability flags\n");
        return NO;
    }
    
    BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);
    BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0);
    return (isReachable && !needsConnection) ? YES : NO;
}

@end
